package com.ssy.lingxi.platform.manage.serviceimpl.content;

import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.constant.ShelfEnum;
import com.ssy.lingxi.platform.manage.entity.content.ContentAdvert;
import com.ssy.lingxi.platform.manage.entity.content.QContentAdvert;
import com.ssy.lingxi.platform.manage.model.request.common.CommonIdRequest;
import com.ssy.lingxi.platform.manage.model.request.common.CommonStatusRequest;
import com.ssy.lingxi.platform.manage.model.request.content.ContentAdvertPageRequest;
import com.ssy.lingxi.platform.manage.model.request.content.ContentAdvertRequest;
import com.ssy.lingxi.platform.manage.repository.ContentAdvertRepository;
import com.ssy.lingxi.platform.manage.service.content.IContentAdvertService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 广告管理 - 业务实现层
 *
 * @author fhj
 * @version 2.0.0
 * @date 2020/9/17
 */
@Service
public class ContentAdvertServiceImpl implements IContentAdvertService {

    @Resource
    private ContentAdvertRepository contentAdvertRepository;
    @Resource
    private JPAQueryFactory jpaQueryFactory;

    @Override
    @ApiOperation(value = "列表")
    public Wrapper<PageData<ContentAdvert>> page(ContentAdvertPageRequest request) {
        QContentAdvert qContentAdvert = QContentAdvert.contentAdvert;
        JPAQuery<ContentAdvert> jpaQuery = jpaQueryFactory.select(qContentAdvert).from(qContentAdvert);

        if (StringUtils.isNotBlank(request.getTitle())) {
            jpaQuery.where(qContentAdvert.title.contains(request.getTitle()));
        }
        if (request.getStatus() != null) {
            jpaQuery.where(qContentAdvert.status.eq(request.getStatus()));
        }
        if (request.getStartTime() != null) {
            jpaQuery.where(qContentAdvert.createTime.goe(request.getStartTime()));
        }
        if (request.getEndTime() != null) {
            jpaQuery.where(qContentAdvert.createTime.loe(request.getEndTime()));
        }

        long totalCount = jpaQuery.fetchCount();
        List<ContentAdvert> list = jpaQuery.orderBy(qContentAdvert.createTime.desc()).limit(request.getPageSize()).offset((long) (request.getCurrent() - 1) * request.getPageSize()).fetch();

        return Wrapper.success(new PageData<>(totalCount, list));
    }

    @Override
    @ApiOperation(value = "详情")
    public Wrapper<ContentAdvert> get(CommonIdRequest request) {
        ContentAdvert contentAdvert = contentAdvertRepository.findById(request.getId()).orElse(null);
        if (contentAdvert == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        return Wrapper.success(contentAdvert);
    }

    @Override
    @Transactional
    @ApiOperation(value = "新增")
    public Wrapper<Void> add(ContentAdvertRequest request, UserLoginCacheDTO user) {
        if (contentAdvertRepository.existsBySortAndColumnType(request.getSort(), request.getColumnType())) {
            return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_SORT_CANNOT_BE_REPEATED);
        }

        ContentAdvert contentAdvert = new ContentAdvert();
        BeanUtils.copyProperties(request, contentAdvert);
        contentAdvertRepository.saveAndFlush(contentAdvert);
        return Wrapper.success();
    }

    @Override
    @Transactional
    @ApiOperation(value = "修改")
    public Wrapper<Void> update(ContentAdvertRequest request, UserLoginCacheDTO user) {
        ContentAdvert existsContentAdvert = contentAdvertRepository.findBySortAndColumnType(request.getSort(), request.getColumnType());
        if (existsContentAdvert != null && existsContentAdvert.getId() - request.getId() != 0) {
            return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_SORT_CANNOT_BE_REPEATED);
        }

        ContentAdvert contentAdvert = contentAdvertRepository.findById(request.getId()).orElse(null);
        if (contentAdvert == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        if (contentAdvert.getStatus().equals(ShelfEnum.ON_SHELF.getCode())) {
            throw new BusinessException(ResponseCode.MAN_DATA_STATUS_INCORRECT_OPERATE_INVALID);
        }
        BeanUtils.copyProperties(request, contentAdvert);
        contentAdvertRepository.saveAndFlush(contentAdvert);
        return Wrapper.success();
    }

    @Override
    @Transactional
    @ApiOperation(value = "上架/下架")
    public Wrapper<Void> updateStatus(CommonStatusRequest request, UserLoginCacheDTO user) {
        ContentAdvert contentAdvert = contentAdvertRepository.findById(request.getId()).orElse(null);
        if (contentAdvert == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        contentAdvert.setStatus(request.getShelfStatus());
        contentAdvertRepository.saveAndFlush(contentAdvert);
        return Wrapper.success();
    }

    @Override
    @Transactional
    @ApiOperation(value = "删除")
    public Wrapper<Void> delete(CommonIdRequest request, UserLoginCacheDTO user) {
        ContentAdvert contentAdvert = contentAdvertRepository.findById(request.getId()).orElse(null);
        if (contentAdvert == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        if (contentAdvert.getStatus().equals(ShelfEnum.ON_SHELF.getCode())) {
            throw new BusinessException(ResponseCode.MAN_DATA_STATUS_INCORRECT_OPERATE_INVALID);
        }
        contentAdvertRepository.delete(contentAdvert);
        return Wrapper.success();
    }

    @Override
    @ApiOperation(value = "根据栏目获取所有")
    public Wrapper<List<ContentAdvert>> findAllByColumnType(Integer columnType) {
        List<ContentAdvert> list = contentAdvertRepository.findAllByStatusAndColumnType(ShelfEnum.ON_SHELF.getCode(), columnType, Sort.by(Sort.Direction.ASC, "sort"));
        return Wrapper.success(list);
    }
}
